package com.rfid.a252robot.admin.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceFragmentCompat;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.rfid.a252robot.R;
import com.rfid.a252robot.admin.ChargePointSelectActivity;
import com.rfid.a252robot.admin.UsbDeviceSelectActivity;
import com.rfid.a252robot.config.AcsConfig;
import com.rfid.a252robot.config.ChargeConfig;
import com.rfid.a252robot.config.GlobalConfig;
import com.rfid.a252robot.net.BoxLibApi;
import com.rfid.a252robot.widget.NoDialogEditPreference;
import com.rfid.manager.DoorBoxManager;
import com.rfid.manager.ReadTagManager;
import com.rfid.util.FileUtil1;
import com.spectre.generate.ConfigManager;
import com.spectre.generate.exception.ConfigFileNotFoundException;

import java.lang.reflect.Field;


public class ConfigFragment extends PreferenceFragmentCompat{

    private PreferenceCategory mGlobal,mAcs,mCharge;
    private String mIp;
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.config_file_preference, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        System.out.println("onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("onDetach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mGlobal = findPreference("global");
        mAcs = findPreference("acs");
        mCharge = findPreference("charge");
        try {
            addConfigPreference();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void addConfigPreference() throws IllegalAccessException {
        mGlobal.removeAll();
        GlobalConfig config = ConfigManager.INSTANCE.getGlobalConfig();
        AcsConfig acsConfig = ConfigManager.INSTANCE.getAcsConfig();
        ChargeConfig chargeConfig = ConfigManager.INSTANCE.getChargeConfig();
        addPreference(mGlobal,config);
        addPreference(mAcs,acsConfig);
        addPreference(mCharge,chargeConfig);
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        String key = preference.getKey();
        if (key.equals("tagReaderVid") || key.equals("tagReaderPid")) {
            Intent intent = new Intent();
            intent.setClass(getContext(), UsbDeviceSelectActivity.class);
            startActivityForResult(intent,1);
            return true;
        } else if (key.equals("doorVid") || key.equals("doorPid")) {
            Intent intent = new Intent();
            intent.setClass(getContext(), UsbDeviceSelectActivity.class);
            startActivityForResult(intent,2);
            return true;
        } else if (key.equals("pointName") || key.equals("mapCode")) {
            Intent intent = new Intent();
            intent.setClass(getContext(), ChargePointSelectActivity.class);
            startActivityForResult(intent,3);
        }
        return super.onPreferenceTreeClick(preference);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("resultCode = " + resultCode + ",requestCode = " + requestCode);
        if (resultCode == 100) {
            if (requestCode == 1) {
                EditTextPreference tagReaderVid = findPreference("tagReaderVid");
                EditTextPreference tagReaderPid = findPreference("tagReaderPid");
                EditTextPreference tagReaderSerialNumber = findPreference("tagReaderSerialNumber");
                tagReaderPid.setText(data.getStringExtra("pid"));
                tagReaderVid.setText(data.getStringExtra("vid"));
                tagReaderSerialNumber.setText(data.getStringExtra("serialNumber"));
                boolean check = DoorBoxManager.INSTANCE.checkDevice(Integer.valueOf(data.getStringExtra("vid"),16),Integer.valueOf(data.getStringExtra("pid"),16));
                if (!check) {
                    Toast.makeText(getContext(),"设备检测不符合串口",Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == 2) {
                EditTextPreference doorVid = findPreference("doorVid");
                EditTextPreference doorPid = findPreference("doorPid");
                EditTextPreference doorSerialNumber = findPreference("doorSerialNumber");
                doorPid.setText(data.getStringExtra("pid"));
                doorVid.setText(data.getStringExtra("vid"));
                doorSerialNumber.setText(data.getStringExtra("serialNumber"));
                boolean check = DoorBoxManager.INSTANCE.checkDevice(Integer.valueOf(data.getStringExtra("vid"),16),Integer.valueOf(data.getStringExtra("pid"),16));
                if (!check) {
                    Toast.makeText(getContext(),"设备检测不符合串口",Toast.LENGTH_SHORT).show();
                }
            } else if (requestCode == 3) {
                EditTextPreference mapCode = findPreference("mapCode");
                EditTextPreference pointName = findPreference("pointName");
                mapCode.setText(data.getStringExtra("mapCode"));
                pointName.setText(data.getStringExtra("pointName"));
            }
        }
    }

    private void addPreference(PreferenceCategory preferenceCategory, Object config) throws IllegalAccessException {
        Class<?> clazz = config.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true); // 设置可访问私有字段
            String name = field.getName();
            Object value = field.get(config);
            System.out.println(name + " = " + value);
            EditTextPreference preference = new EditTextPreference(getContext());
            if (name.equals("tagReaderVid") || name.equals("tagReaderPid") || name.equals("doorVid") || name.equals("doorPid") || name.equals("mapCode") || name.equals("pointName")) {
                preference = new NoDialogEditPreference(getContext());
            }
            preference.setTitle(name);
            preference.setKey(name);
            if (value != null) {
                preference.setText(value.toString());
            }
            preference.setPersistent(false);
            preference.setIconSpaceReserved(false);
            preference.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
            preferenceCategory.addPreference(preference);
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.config,menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        System.out.println("onOptionsItemSelected id = " + id);
        if (id == R.id.save) {
            String gjson = getConfig(mGlobal);
            String ajson = getConfig(mAcs);
            String cjson = getConfig(mCharge);
            FileUtil1.writeFile("/sdcard/robot/config/global.json",gjson);
            FileUtil1.writeFile("/sdcard/robot/config/acs.json",ajson);
            FileUtil1.writeFile("/sdcard/robot/config/charge.json",cjson);
            try {
                ConfigManager.INSTANCE.init();
                BoxLibApi.INSTANCE.init();
                DoorBoxManager.INSTANCE.init(getContext());
                DoorBoxManager.INSTANCE.prepareReadWrite();
                ReadTagManager.INSTANCE.findDevice();
                ReadTagManager.INSTANCE.prepareReadTag();
                Toast.makeText(getContext(),"保存成功",Toast.LENGTH_SHORT).show();
            } catch (ConfigFileNotFoundException e) {
                e.printStackTrace();
            }
            AcsConfig config = com.spectre.generate.ConfigManager.INSTANCE.getAcsConfig();
            com.rfid.manager.ConfigManager.INSTANCE.initTcpClient(config.getIp(), config.getPort(), config.getDeviceNo());
        }
        return super.onOptionsItemSelected(item);
    }

    private String getConfig(PreferenceCategory category) {
        int count = category.getPreferenceCount();
        JsonObject jsonObject = new JsonObject();
        for (int i=0;i<count;i++) {
            Preference preference = category.getPreference(i);
            if (preference instanceof EditTextPreference) {
                String key = preference.getKey();
                String value = ((EditTextPreference) preference).getText();
                if (TextUtils.isEmpty(value)) {
                    jsonObject.add(key,null);
                    continue;
                }
                if (value.contains("[")&&value.contains("]")) {
                    value = value.replace("[","").replace("]","").replace("\"","");
                    String arrs[] = value.split(",");
                    JsonArray array = new JsonArray();
                    for (String a : arrs) {
                        array.add(a);
                    }
                    jsonObject.add(key,array);
                } else {
                    jsonObject.addProperty(key,value);
                }
            }
        }
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }
}
